﻿//Created by Action Script Viewer - http://www.buraks.com/asv
package Classes {
    import flash.events.*;
    import Engine.Events.*;
    import flash.display.*;
    import Events.*;
    import Display.DialogUI.*;
    import org.aswing.*;
    import Transactions.*;
    import Classes.util.*;
    import flash.filters.*;
    import org.aswing.geom.*;
    import Modules.quest.Managers.*;
    import Display.*;
    import Display.MarketUI.*;
    import GameMode.*;
    import Classes.doobers.*;
    import Modules.stats.experiments.*;
    import Display.aswingui.*;
    import Modules.stats.types.*;
    import Modules.quest.Helpers.*;

    public class Plot extends HarvestableResource {

        private static var m_catalogWindow:Catalog;
        private static var marketClickedPlot:Plot = null;

        private const PLOT:String = "plot";
        private const WITHERED_HIGHLIGHT_COLOR:uint = 0xAA0000;

        private var m_itemImageName:String;
        private var m_isNewPlot:Boolean = true;
        private var m_isPlowing:Boolean = false;

        public function Plot(_arg1:String=null, _arg2:int=0){
            super(_arg1);
            m_objectType = WorldObjectTypes.PLOT;
            m_typeName = this.PLOT;
        }
        public static function get IsMarketClickedPlotSet():Boolean{
            return (!((marketClickedPlot == null)));
        }
        private static function SetMarketClickedPlot(_arg1:Plot):void{
            marketClickedPlot = _arg1;
        }
        public static function ResetMarketClickedPlotSet():void{
            marketClickedPlot = null;
        }
        public static function SetContactToMarketClickedPlot(_arg1:String):void{
            marketClickedPlot.plant(_arg1);
            ResetMarketClickedPlotSet();
        }

        override public function get harvestingDefinition():Item{
            return (((m_contract)!=null) ? m_contract : m_item);
        }
        override public function getSaveObject():Object{
            this.m_isNewPlot = false;
            var _local1:Object = super.getSaveObject();
            if (m_contract){
                _local1.contractName = m_contract.name;
                _local1.contractType = m_contract.type;
            };
            return (_local1);
        }
        override public function loadObject(_arg1:Object):void{
            this.m_isNewPlot = false;
            m_contract = Global.gameSettings.getItemByName(_arg1.contractName);
            m_contractGrowTime = (m_contract) ? m_contract.growTime : 0;
            super.loadObject(_arg1);
        }
        protected function getPlotImage():ItemImageInstance{
            return (super.getCurrentImage());
        }
        protected function getContractImage():ItemImageInstance{
            var _local1:ItemImageInstance = m_contract.getCachedImage(m_state, this, m_direction, m_statePhase);
            if (_local1 == null){
                m_contract.addEventListener(LoaderEvent.LOADED, this.onContractImageLoaded, false, 0, true);
            };
            return (_local1);
        }
        override protected function getCurrentImage():ItemImageInstance{
            if (m_contract == null){
                return (this.getPlotImage());
            };
            return (this.getContractImage());
        }
        override protected function getPlowedCursor():Class{
            return (EmbeddedArt.hud_act_plant);
        }
        override protected function getGrownCursor():Class{
            if (((!(m_isHarvesting)) && (Global.player.checkEnergy(-(m_contract.harvestEnergyCost), false)))){
                return (EmbeddedArt.hud_act_harvest);
            };
            return (null);
        }
        override public function get isHighlightable():Boolean{
            return (((super.isHighlightable) && (((!((m_state == STATE_PLANTED))) || (Global.world.isEditMode)))));
        }
        override protected function isWrongPlantContract():Boolean{
            var _local1:GMPlant = GMPlant(Global.world.getTopGameMode());
            if (_local1.m_contractClass == "plot_contract"){
                return (false);
            };
            return (true);
        }
        override public function getHighlightColor():uint{
            if (m_state == STATE_WITHERED){
                return (this.WITHERED_HIGHLIGHT_COLOR);
            };
            return (super.getHighlightColor());
        }
        override protected function get isUxLockedByQuests():Boolean{
            return (((!((Global.questManager == null))) && (!(Global.questManager.isUXUnlocked(GameQuestManager.QUEST_UX_CROPS_UNLOCKED)))));
        }
        protected function onContractImageLoaded(_arg1:LoaderEvent):void{
            _arg1.target.removeEventListener(LoaderEvent.LOADED, this.onContractImageLoaded);
            reloadImage();
        }
        override protected function computeStatePhase():String{
            if (m_state == STATE_PLANTED){
                return (("" + (1 + int(Math.floor((m_growPercentage / 51))))));
            };
            return (Item.DEFAULT_PHASE);
        }
        override public function getToolTipHeader():String{
            var _local1:String = this.getContractFriendlyName();
            if (!_local1){
                if ((Global.world.getTopGameMode() is GMPlant)){
                    if (this.isWrongPlantContract()){
                        return (null);
                    };
                };
                return (super.getToolTipHeader());
            };
            return (_local1);
        }
        protected function getVisitToolTipAction():String{
            var _local1:String;
            if (Global.player.checkVisitorEnergy(1)){
                switch (m_state){
                    case STATE_GROWN:
                        _local1 = ZLoc.t("Main", "GrownAction");
                        break;
                    case STATE_PLANTED:
                        _local1 = ZLoc.t("Main", "PlantedPlotVisitor");
                        break;
                    case STATE_WITHERED:
                        _local1 = ZLoc.t("Main", "WitheredPlotVisitor");
                        break;
                };
            } else {
                _local1 = ZLoc.t("Main", "NeedEnergy", {amount:1});
            };
            return (_local1);
        }
        protected function getPlowedToolTipAction():String{
            var _local1:String;
            if ((Global.world.getTopGameMode() is GMPlant)){
                if (this.isWrongPlantContract()){
                    return (null);
                };
            };
            _local1 = ZLoc.t("Main", "PlowedPlotAction");
            return (_local1);
        }
        override public function getToolTipAction():String{
            var _local1:String = getGameModeToolTipAction();
            if (!_local1){
                _local1 = super.getToolTipAction();
                if (Global.isVisiting()){
                    _local1 = this.getVisitToolTipAction();
                } else {
                    if (m_state == STATE_GROWN){
                        _local1 = getGrownToolTipAction();
                        if (!Global.player.checkEnergy(-(m_contract.harvestEnergyCost), false)){
                            _local1 = ZLoc.t("Main", "NeedEnergy", {amount:m_contract.harvestEnergyCost});
                        };
                    };
                    if (m_state == STATE_PLOWED){
                        _local1 = this.getPlowedToolTipAction();
                    };
                    if (m_isHarvesting){
                        _local1 = null;
                    };
                };
            };
            return (_local1);
        }
        override public function getCustomCursor():Object{
            var _local2:ASFont;
            var _local3:GlowFilter;
            var _local4:MarginBackground;
            if (m_isHarvesting){
                return (null);
            };
            if (!m_customCursor){
                m_customCursor = ASwingHelper.makeSoftBoxJPanel(SoftBoxLayout.CENTER);
                m_customCursorLabel = new JLabel("");
                m_customCursorHolder = new Sprite();
                Global.ui.addChild(m_customCursorHolder);
                m_customCursorWindow = new JWindow(m_customCursorHolder);
                _local2 = ASwingHelper.getBoldFont(16);
                _local3 = new GlowFilter(0, 1, 1.2, 1.2, 20, BitmapFilterQuality.HIGH);
                m_customCursorLabel.setForeground(new ASColor(0xFFFFFF));
                m_customCursorLabel.setFont(_local2);
                m_customCursorLabel.setTextFilters([_local3]);
            };
            var _local1:DisplayObject;
            if (m_state == STATE_GROWN){
                _local1 = (new EmbeddedArt.hud_act_harvest() as DisplayObject);
                m_customCursorLabel.setText(m_contract.harvestEnergyCost.toString());
                m_customCursorLabel.visible = true;
            } else {
                return (null);
            };
            if (_local1){
                _local4 = new MarginBackground(_local1, new Insets(0, 0, 0, 0));
                m_customCursor.setBackgroundDecorator(_local4);
                m_customCursor.setPreferredSize(new IntDimension(_local1.width, _local1.height));
                m_customCursor.setMinimumSize(new IntDimension(_local1.width, _local1.height));
                m_customCursor.setMaximumSize(new IntDimension(_local1.width, _local1.height));
            };
            m_customCursor.append(m_customCursorLabel);
            m_customCursorWindow.setContentPane(m_customCursor);
            ASwingHelper.prepare(m_customCursorWindow);
            m_customCursorWindow.show();
            return (m_customCursorWindow);
        }
        protected function showCatalogWindow():Catalog{
            return (UI.displayCatalog("plot_contract", null, true, "plot_contract", true, false, true));
        }
        protected function processPlantedState():void{
            var _local2:DisplayObject;
            var _local1:int = Global.experimentManager.getVariant(ExperimentDefinitions.EXPERIMENT_INSTANT_READY_CROPS_SHIPS);
            if (((((!(Global.isVisiting())) && ((Global.player.level >= 6)))) && ((_local1 > 1)))){
                _local2 = new InstantReadyDialog(this);
                UI.displayPopup(_local2, true, "instantReadyCrops", false);
            };
        }
        override public function onPlayAction():void{
            var _local1:Number;
            if (this.isUxLockedByQuests){
                displayStatus(ZLoc.t("Main", "QuestUXLocked"));
                return;
            };
            if ((((m_visitReplayLock > 0)) || (Global.isVisiting()))){
                return;
            };
            if (!hasValidId()){
                showObjectBusy();
                return;
            };
            super.onPlayAction();
            m_actionMode = PLAY_ACTION;
            switch (m_state){
                case STATE_PLOWED:
                    if (Global.guide.isActive()){
                        break;
                    };
                    if (UI.resolveIfAssetsHaveNotLoaded(DelayedAssetLoader.MARKET_ASSETS)){
                        break;
                    };
                    SetMarketClickedPlot(this);
                    m_catalogWindow = this.showCatalogWindow();
                    if (((m_catalogWindow) && (!(m_catalogWindow.hasEventListener(Event.CLOSE))))){
                        m_catalogWindow.addEventListener(Event.CLOSE, this.onMarketCloseClick);
                    };
                    break;
                case STATE_PLANTED:
                    this.processPlantedState();
                    break;
                case STATE_GROWN:
                    _local1 = m_contract.harvestEnergyCost;
                    if (!Global.player.checkEnergy(-(_local1))){
                        displayStatus(ZLoc.t("Main", "NotEnoughEnergyRed"));
                    } else {
                        if (!m_isHarvesting){
                            if (!isHarvestable()){
                                break;
                            };
                            if (Global.player.commodities.isAtCommodityCapacity(m_contract)){
                                m_firstHarvestAttempt = false;
                                break;
                            };
                            m_isHarvesting = true;
                            setHighlighted(false);
                            Global.world.citySim.pickupManager.enqueue("NPC_farmer", this);
                        };
                    };
                    break;
                case STATE_FALLOW:
                case STATE_WITHERED:
                    if (!this.m_isPlowing){
                        this.m_isPlowing = true;
                        setHighlighted(false);
                        Global.world.citySim.pickupManager.enqueue("NPC_farmer", this);
                    };
                    break;
            };
        }
        override public function onVisitPlayAction():void{
            switch (m_state){
                case STATE_PLANTED:
                    Global.world.citySim.pickupManager.enqueue("NPC_farmer", this);
                    break;
                case STATE_GROWN:
                    if (isHarvestable()){
                        m_isHarvesting = true;
                        setHighlighted(false);
                        Global.world.citySim.pickupManager.enqueue("NPC_farmer", this);
                    };
                    break;
                case STATE_WITHERED:
                    Global.world.citySim.pickupManager.enqueue("NPC_farmer", this);
                    break;
            };
        }
        override public function onVisitReplayAction(_arg1:TRedeemVisitorHelpAction):Number{
            m_actionMode = VISIT_REPLAY_ACTION;
            switch (m_state){
                case STATE_PLANTED:
                    break;
                case STATE_GROWN:
                    if (((isHarvestable()) && (!(m_isHarvesting)))){
                        m_isHarvesting = true;
                        setHighlighted(false);
                    } else {
                        return (0);
                    };
                    break;
                case STATE_WITHERED:
                    break;
                default:
                    return (0);
            };
            if (!this.stopTransaction()){
                GameTransactionManager.addTransaction(_arg1);
            };
            getProgressBarEndFunction()();
            return (super.onVisitReplayAction(null));
        }
        private function stopTransaction():Boolean{
            var _local1:Boolean;
            if (((((!(Global.isVisiting())) && (!((this.getState() == STATE_PLANTED))))) && (!((this.getState() == STATE_WITHERED))))){
                if (Global.player.commodities.isAtCommodityCapacity(m_contract, false)){
                    _local1 = true;
                };
            };
            return (_local1);
        }
        override public function isVisitorInteractable():Boolean{
            switch (m_state){
                case STATE_PLANTED:
                    return (true);
                case STATE_GROWN:
                    if (((isHarvestable()) && (!(Global.player.commodities.isAtCommodityCapacity(m_contract))))){
                        return (true);
                    };
                    return (false);
                case STATE_WITHERED:
                    return (true);
            };
            return (false);
        }
        protected function cancelContractHandler(_arg1:GenericPopupEvent):void{
            if (_arg1.button != GenericPopup.YES){
                return;
            };
            GameTransactionManager.addTransaction(new TFactoryContractCancel(this));
            if ((m_contract is Item)){
                displayStatus(ZLoc.t("Main", "FactoryCancelContractSuccess", {crop:m_contract.localizedName}));
                m_contract = null;
            };
            setState(STATE_PLOWED);
        }
        protected function onMarketCloseClick(_arg1:Event):void{
            if (m_catalogWindow){
                m_catalogWindow.removeEventListener(Event.CLOSE, this.onMarketCloseClick);
            };
            m_catalogWindow = null;
        }
        override public function plow():Boolean{
            var _local2:int;
            var _local3:int;
            var _local1:Boolean;
            if (isWithered()){
                m_doobersArray = this.makeDoobers();
                spawnDoobers();
                setState(STATE_PLOWED);
                GameTransactionManager.addTransaction(new TClearWithered(this));
                trackAction(TrackedActionType.CLEAR);
                this.m_isPlowing = false;
                return (true);
            };
            if (isPlowable()){
                _local2 = Global.gameSettings.getInt("plowCost");
                _local3 = Global.gameSettings.getInt("plowXp");
                if (Global.player.canBuy(_local2)){
                    doResourceChanges(0, -(_local2), _local3);
                    setState(STATE_PLOWED);
                    GameTransactionManager.addTransaction(new TPlow(this), true);
                    _local1 = true;
                } else {
                    if (((this.m_isNewPlot) && ((m_state == STATE_FALLOW)))){
                        detach();
                    };
                };
            };
            return (_local1);
        }
        override protected function makeDoobers(_arg1:Number=1):Array{
            var _local3:int;
            var _local2:Array = new Array();
            if (m_state == STATE_WITHERED){
                _local3 = (this.harvestingDefinition.cost * Global.gameSettings.getNumber("witherRefundMultiplier"));
                _local2.push(new Array(Global.gameSettings.getDooberFromType(Doober.DOOBER_COIN, _local3), _local3));
            } else {
                _local2 = Global.player.processRandomModifiers(this.harvestingDefinition, this, true, m_secureRands);
            };
            return (_local2);
        }
        override public function harvest():Boolean{
            var _local1:Boolean;
            var _local2:Boolean;
            m_isHarvesting = false;
            if (!isHarvestable()){
                return (false);
            };
            if (!Global.isVisiting()){
                _local1 = false;
                _local2 = false;
                if (((m_firstHarvestAttempt) && (!((m_actionMode == VISIT_REPLAY_ACTION))))){
                    _local1 = true;
                };
                if (m_actionMode == VISIT_REPLAY_ACTION){
                    _local2 = true;
                };
                if (Global.player.commodities.isAtCommodityCapacity(m_contract, _local1)){
                    m_firstHarvestAttempt = false;
                    if (_local2){
                        displayStatus(ZLoc.t("Main", "NeedMoreStorage"));
                    };
                    return (false);
                };
            };
            m_firstHarvestAttempt = true;
            Sounds.playFromSet(Sounds.SET_HARVEST, this);
            if (!Global.isVisiting()){
                m_doobersArray = this.makeDoobers();
                spawnDoobers();
                if (m_actionMode != VISIT_REPLAY_ACTION){
                    GameTransactionManager.addTransaction(new THarvest(this));
                    trackAction(TrackedActionType.HARVEST);
                    Global.player.heldEnergy = (Global.player.heldEnergy - m_heldEnergy);
                };
            } else {
                onVisitorHelp(STATE_GROWN);
            };
            setState(STATE_PLOWED);
            plantTime = 0;
            return (true);
        }
        override public function revive():Boolean{
            NeighborVisitManager.setVisitFlag(NeighborVisitManager.VISIT_REVIVEDCROPS);
            return (super.revive());
        }
        override public function getCoinYield():int{
            var _local1:Number = ((m_contract)!=null) ? m_contract.coinYield : m_item.coinYield;
            return (Math.floor(_local1));
        }
        override public function getXpYield():int{
            var _local1:Number = ((m_contract)!=null) ? m_contract.xpYield : m_item.xpYield;
            return (Math.floor(_local1));
        }
        override protected function friendVisitRepGain():int{
            return (Global.gameSettings.getInt("friendVisitPlotRepGain", 1));
        }
        override public function doHarvestDropOff(_arg1:Boolean=true):Object{
            if (((_arg1) && (m_contract))){
                displayDelayedResourceChanges();
            };
            m_contract = null;
            return (super.doHarvestDropOff(_arg1));
        }
        override public function plant(_arg1:String):Boolean{
            var _local3:Item;
            var _local4:int;
            var _local5:int;
            var _local6:int;
            var _local7:Boolean;
            var _local2:Boolean;
            if (isPlantable(_arg1)){
                _local3 = Global.gameSettings.getItemByName(_arg1);
                if (((((_local3) && ((_local3.type == "plot_contract")))) || ((_local3.type == "factory_contract")))){
                    _local4 = _local3.cost;
                    _local5 = _local3.cash;
                    _local6 = _local3.plantXp;
                    _local7 = false;
                    if ((((_local5 > 0)) && (Global.player.canBuyCash(_local5)))){
                        Global.player.cash = (Global.player.cash - _local5);
                        _local7 = true;
                    } else {
                        if ((((_local4 > 0)) && (Global.player.canBuy(_local4)))){
                            Global.player.gold = (Global.player.gold - _local4);
                            _local7 = true;
                        };
                    };
                    if (_local7){
                        Global.player.xp = (Global.player.xp + _local6);
                        plantTime = GlobalEngine.getTimer();
                        Sounds.playFromSet(Sounds.SET_PLANT);
                        m_contract = _local3;
                        m_contractGrowTime = _local3.growTime;
                        m_witherOn = _local3.allowWither;
                        setState(STATE_PLANTED);
                        GameTransactionManager.addTransaction(new TFactoryContractStart(this), true);
                        trackAction(TrackedActionType.PLANT);
                        _local2 = true;
                    };
                };
            } else {
                if (!hasValidId()){
                    showObjectBusy();
                };
            };
            if (_local2){
                this.adjustModesAfterPlanting();
            };
            return (_local2);
        }
        protected function adjustModesAfterPlanting():void{
            var _local2:Plot;
            var _local1:Array = Global.world.getObjectsByClass(Plot);
            for each (_local2 in _local1) {
                if ((((_local2.getItem().type == "plot")) && ((_local2.m_state == STATE_PLOWED)))){
                    return;
                };
            };
            if ((Global.world.getTopGameMode() is GMPlant)){
                Global.world.addGameMode(new GMPlay());
            };
        }
        override protected function getContractFriendlyName():String{
            if (!m_contract){
                return ("");
            };
            return (ZLoc.t("Items", (m_contract.name + "_friendlyName")));
        }
        override public function getHarvestTime():Number{
            if (((!(Global.isVisiting())) && ((m_state == STATE_WITHERED)))){
                return (Global.gameSettings.getNumber("actionBarCropClear"));
            };
            return (Global.gameSettings.getNumber("actionBarPlotActions"));
        }
        override public function getActionText():String{
            if ((((m_state == STATE_PLANTED)) && (!((((m_actionMode == VISIT_PLAY_ACTION)) || ((m_actionMode == VISIT_REPLAY_ACTION))))))){
                return (getFinishingText());
            };
            return (super.getActionText());
        }
        override public function getProgressBarStartFunction():Function{
            var harvestResource:* = null;
            harvestResource = this;
            return (function ():Boolean{
                var _local1:*;
                if (!Global.isVisiting()){
                    if (m_actionMode != VISIT_REPLAY_ACTION){
                        switch (m_state){
                            case STATE_PLANTED:
                                break;
                            case STATE_GROWN:
                                _local1 = m_contract.harvestEnergyCost;
                                if (m_actionMode == VISIT_REPLAY_ACTION){
                                    _local1 = 0;
                                };
                                if (!Global.player.checkEnergy(-(_local1))){
                                    return (false);
                                };
                                if (Global.player.commodities.isAtCommodityCapacity(m_contract)){
                                    return (false);
                                };
                                Sounds.playFromSet(Sounds.SET_HARVEST, harvestResource);
                                doEnergyChanges(-(_local1), new Array("energy", "expenditures", "harvest_crop", harvestingDefinition.name));
                                Global.player.heldEnergy = (Global.player.heldEnergy + _local1);
                                m_heldEnergy = _local1;
                                break;
                            case STATE_WITHERED:
                                Sounds.playFromSet(Sounds.SET_HARVEST, harvestResource);
                                break;
                        };
                    } else {
                        Sounds.playFromSet(Sounds.SET_HARVEST, harvestResource);
                    };
                } else {
                    switch (m_state){
                        case STATE_PLANTED:
                            trackVisitAction(TrackedActionType.WATER_CROP);
                            m_lastVisitorHelpType = VisitorHelpType.PLOT_WATER;
                            m_numVisitorInteractions++;
                            Sounds.playFromSet(Sounds.SET_HARVEST, harvestResource);
                            break;
                        case STATE_GROWN:
                            if (Global.player.commodities.isAtCommodityCapacity(m_contract)){
                                return (false);
                            };
                            trackVisitAction(TrackedActionType.HARVEST_CROP);
                            m_lastVisitorHelpType = VisitorHelpType.PLOT_HARVEST;
                            m_numVisitorInteractions++;
                            Sounds.playFromSet(Sounds.SET_HARVEST, harvestResource);
                            break;
                        case STATE_WITHERED:
                            trackVisitAction(TrackedActionType.REVIVE_CROP);
                            m_lastVisitorHelpType = VisitorHelpType.PLOT_REVIVE;
                            m_numVisitorInteractions++;
                            Sounds.playFromSet(Sounds.SET_HARVEST, harvestResource);
                            break;
                    };
                };
                return (true);
            });
        }
        override public function getProgressBarCancelFunction():Function{
            return (function ():void{
                m_isHarvesting = false;
                Global.player.heldEnergy = (Global.player.heldEnergy - m_heldEnergy);
            });
        }
        override public function getVisitReplayEquivalentActionString():String{
            var _local1 = "";
            switch (this.getState()){
                case STATE_GROWN:
                    _local1 = "harvest";
                    break;
                case STATE_PLANTED:
                case STATE_WITHERED:
                    break;
            };
            return (_local1);
        }

    }
}//package Classes 
